const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');
const rp = require('./requestProxy');
const isArray = require('lodash/lang/isArray');
const remove = require('lodash/array/remove');
const markdown = require('markdown').markdown;

const router = express.Router();


const dataBuilder = require('./dataBuilder');

const dicCondition = require('./dicCondition');
const dicAPIUrl = require('./dicAPIUrl');

const __DEV__ = process.env.NODE_ENV == 'dev';

// parse application/json
router.use(bodyParser.json());

// 筛选条件
// /api/condition/key/value
router.get(/^\/condition\/([\w|-]+)\/(\w+)$/, (req, res) => {
	'use strict';

	let key = req.params[0];
	let value = req.params[1];

	try {
		let parameter = dicCondition[key](value);

		rp.post(dicAPIUrl['condition'], parameter)
			.then((data) => {
				if (isArray(data)) {
					let evens = remove(data, (n) => n.name == '未知');
					if (evens.length != 0) {
						data.push(evens[0]);
					}
				}
				res.json(rp.dataPack(data));
			})
			.catch((err) => {
				res.json(rp.dataPack(err, true));
			});
	} catch (e) {
		res.status(500).json(rp.dataPack(`无法获取筛选条件: ${key}/${value} with '${e.message}'`, true));
	}
});

// 图表数据
router.post('/data/:chartName', (req, res) => {
	'use strict';

	let chartName = req.params.chartName;
	let parameters = [];
	let postRequestData = undefined, api = undefined, responseHandler;

	try {
		let builder = dataBuilder.createDataBuilder(chartName);
		postRequestData = builder.request(req.body);
		api = builder.API_URL;
		responseHandler = builder.response;

		if (!postRequestData || postRequestData.length == 0) {
			throw new Error('builder.request 返回值不能为空.')
		}
		if (!api) {
			throw new Error('builder.api 不能为空.')
		}
		if (!responseHandler) {
			throw new Error('builder.response 不能为空')
		}
	} catch (e) {
		return res.status(500).json(rp.dataPack(`无法获取图表数据: ${chartName} with '${e.message}'`, true));
	}

	rp.post(api, postRequestData)
		.then((data) => {
			if (__DEV__) {
				console.log('>>>>>>>>>>>>>>> 请求成功 <<<<<<<<<<<<<')
				console.log(`请求地址: ${api}`);
				console.log(`请求数据: `, JSON.stringify(postRequestData));
				console.log(`返回数据: `, data);
				console.log('>>>>>>>>>>>>>>> END <<<<<<<<<<<<<');
			}
			let result = responseHandler.apply(null, data)
			res.status(200).json(rp.dataPack(result));
		})
		.catch((error) => {
			if (__DEV__) {
				console.log('>>>>>>>>>>>>>>> 出现错误 <<<<<<<<<<<<<')
				console.log(`请求地址: ${api}`);
				console.log(`请求数据: `, JSON.stringify(postRequestData));
				console.log(`错误信息: ${error.message || error.toString()}`);
				console.log(`调用堆栈:`, error.stack);
				console.log('>>>>>>>>>>>>>>> END <<<<<<<<<<<<<');
			}

			res.status(500).json(rp.dataPack(`无法获取图表数据: ${chartName} with '${error.message || error.toString()}'`, true))
		});

	// postRequestData.forEach((item, index) => {
	// 	rp.post(api, item)
	// 		.then(function(requestData, api, index, data) {
	// 			if (__DEV__) {
	// 				console.log('>>>>>>>>>>>>>>> 请求成功 <<<<<<<<<<<<<')
	// 				console.log(`请求地址: ${api}`);
	// 				console.log(`请求数据: `, requestData);
	// 				console.log(`返回数据:`, data);
	// 				console.log('>>>>>>>>>>>>>>> END <<<<<<<<<<<<<');
	// 			}

	// 			parameters[index] = data;

	// 			let length = parameters.reduce((count, item) => {
	// 				if (item) {
	// 					count++;
	// 				}

	// 				return count;
	// 			}, 0);

	// 			if (length == postRequestData.length) {
	// 				let result = responseHandler.apply(null, parameters);
	// 				res.json(rp.dataPack(result));
	// 			}
	// 		}.bind(this, item, api, index))
	// 		.catch(function(requestData, api, err) {
	// 			if (!res.headersSent) {
	// 				res.status(500).json(rp.dataPack(`无法获取图表数据: ${chartName} with '${err}'`, true));
	// 			}

	// 			if (__DEV__) {
	// 				console.log('>>>>>>>>>>>>>>> 出现错误 <<<<<<<<<<<<<')
	// 				console.log(`请求地址: ${api}`);
	// 				console.log(`请求数据: `, requestData);
	// 				console.log(`调用堆栈:`, err.stack);
	// 				console.log('>>>>>>>>>>>>>>> END <<<<<<<<<<<<<');
	// 			}
	// 		}.bind(this, item, api))
	// });
});

router.get('/changelog', (req, res) => {
	fs.readFile(path.join(__dirname, '../changelog.md'), { encoding: 'utf-8'}, (err, data) => {
		if (err) return res.send(err);

		res.send(markdown.toHTML(data.toString()));
	})
});

module.exports = router;
